package com.keepers.repair.utils

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.keepers.repair.R
import com.keepers.repair.model.ServerModel
import com.keepers.repair.model.UserModel
import com.keepers.repair.model.XmlRootModel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.defaultSharedPreferences
import retrofit2.adapter.rxjava2.Result

/**
 * 在 sharedPreference 中获取一个对象
 * @param key
 * @param default
 */
inline fun <reified T> SharedPreferences.getObject(key: String, default: T?): T? {
    val gson = Gson()
    val objStr = this.getString(key, null)
    return try {
        gson.fromJson<T>(objStr, T::class.java)
    } catch (e: Exception) {
        e.printStackTrace()
        default
    }
}

/**
 * 在 sharedPreference 中写入一个对象
 * @param key
 * @param obj
 */
fun <T> SharedPreferences.Editor.putObject(key: String, obj: T): SharedPreferences.Editor {
    val gson = Gson()
    val objStr = gson.toJson(obj)
    this.putString(key, objStr)
    return this
}

/**
 * Observable 对象的通用网络请求过程
 * @param successCallback 请求成功的回调
 * @param failedCallback  请求失败的回调
 */
internal fun Observable<Result<XmlRootModel>>.call(
    successCallback: ((Result<XmlRootModel>) -> Unit),
    failedCallback: (Throwable) -> Unit
) {
    this.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({ result ->
            if (result.isError) {
                throw result.error()!!
            }
            successCallback(result)
        }, { err ->
            err.printStackTrace()
            failedCallback(err)
        })
}

/**
 * Observable 对象的通用网络请求过程
 * @param successCallback 请求成功的回调
 */
internal fun Observable<Result<XmlRootModel>>.call(successCallback: ((Result<XmlRootModel>) -> Unit)) {
    this.call(successCallback) {}
}

/**
 * 登录对象
 */
var Context.logined: UserModel?
    get() = this.defaultSharedPreferences.getObject<UserModel>("user", null)
    set(user) {
        val edit = this.defaultSharedPreferences.edit()
        if (user != null) {
            edit.putObject("user", user)
        } else {
            edit.putString("user", null)
        }
        edit.apply()
    }

/**
 * 服务器配置对象
 */
val Context.server: ServerModel
    get() {
        val host = SpUtils.getString(getString(R.string.settings_key_server_host))
        val port = SpUtils.getString(getString(R.string.settings_key_server_port))
        return if (host != null && port != null) {
            ServerModel(host, port.toInt())
        } else {
            SpUtils.put(getString(R.string.settings_key_server_host), Config.httpHost)
            SpUtils.put(getString(R.string.settings_key_server_port), Config.httpPort.toString())
            defaultServerConfig
        }
    }
